/**
 * @author：ww
 * @function: 对象深度拷贝
 * @pramas: obj 需要拷贝的对象 必填
 *            newobj 拷贝生成的对象 非必填
 */
import {Message} from 'element-ui';

const deepCopy = function (source) {
    if (Array.isArray(source)) {
        const result = [];
        for (const key in source) {
            result[key] = typeof source[key] === 'object' ? deepCopy(source[key]) : source[key];
        }
        return result;
    } else {
        const result = {};
        for (const key in source) {
            result[key] = typeof source[key] === 'object' && source[key] != null ? deepCopy(source[key]) : source[key];
        }
        return result;
    }
}

/**
 * @author：px
 * @function: 对象合并操作
 */
const merge = function (dest, res) {
    return Object.assign({}, dest, res)
}
/**
 * @author：px
 * @function: 对象属性排序
 */
const objKeySort = function (arys, fn) {
    //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    const newkey = Object.keys(arys).sort(fn);
    const newObj = {}; //创建一个新的对象，用于存放排好序的键值对
    for (let i = 0; i < newkey.length; i++) {
        //遍历newkey数组
        newObj[newkey[i]] = arys[newkey[i]];
        //向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj; //返回排好序的新对象
}
/**
 * @author：px
 * @function: 对象属性排序
 */
const objValSort = function (arys, fn) {
    const tmp = Object.assign({}, arys)
    for (const name in tmp) {
        if (tmp.hasOwnProperty(name)) {
            tmp[name]._name = name
        }
    }

    const newVal = fn ? Object.values(tmp).sort(fn) : Object.values(tmp).sort()

    const newObj = {}
    for (const val of newVal) {
        newObj[val._name] = val
    }
    return newObj; //返回排好序的新对象
}

const convert10To26 = function (num) {
    let code = '';
    const reg = /^\d+$/g;
    if (!reg.test(num)) {
        return code;
    }
    while (num > 0) {
        let m = num % 26
        if (m == 0) {
            m = 26;
        }
        code = String.fromCharCode(64 + parseInt(m)) + code;
        num = (num - m) / 26;
    }
    return code;
}

const convert26To10 = function (code) {
    let num = -1;
    const reg = /^[A-Z]+$/g;
    if (!reg.test(code)) {
        return num;
    }
    num = 0;
    for (let i = code.length - 1, j = 1; i >= 0; i-- , j *= 26) {
        num += (code[i].charCodeAt() - 64) * j;
    }
    return num;
}

const readerOnload = function (resolve) {
    return function (e) {
        resolve(e.target.result)
    }
}

const handleFile = function (input) {
    const promises = []
    const files = input.files
    for (let i = 0; i < files.length; ++i) {

        const promise = new Promise((resolve) => {
            const f = files[i]
            const reader = new FileReader()
            reader.onload = readerOnload(resolve)
            reader.readAsBinaryString(f)
        })
        promises.push(promise)
    }
    return Promise.all(promises)
}

/**
 * @author：ww
 * @function: 时间格式化
 * @pramas: 1."times": 可以为秒或者毫秒，必填
 2."formatStr": 返回时间格式 非必填
 */
const dateFormat = function (times, formatStr) {
    let timestamp;
    if (/^(\-|\+)?\d{12,15}$/.test(times)) {
        timestamp = times;
    } else if (/^\d{9,11}$/.test(times)) {
        timestamp = times * 1000;
    } else {
        return times;
    }
    let format = formatStr || 'yyyy/MM/dd'
    let currentDate = new Date(timestamp)
    // if(currentDate.getFullYear()<1901) { // 加100年将上海时间转化成北京时间
    //   currentDate = new Date(timestamp+100*365*24*3600*1000);
    // }
    const date = {
        "M+": currentDate.getMonth() + 1,
        "d+": currentDate.getDate(),
        "h+": currentDate.getHours(),
        "m+": currentDate.getMinutes(),
        "s+": currentDate.getSeconds()
    }
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (currentDate.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

/**
 * @author：zhf
 * @pramas: time String  需格式化的时间 ex:201801020901
 *
 */
const formatPibTime = function (time) {
    if (time) {
        return `${time.substring(0, 4)}-${time.substring(4, 6)}-${time.substring(6, 8)} ${time.substring(8, 10)}:${time.substring(10, 12)}`
    }
}

/**
 * @author：zhf
 * @pramas: time String  需格式化的时间 ex:2021-5-26
 *
 */
const getTimeFormat = function (time) {
    if (time) {
        return new Date(time).getTime();
    }
}
/**
 * @author：qm
 * @function: 限制小数位
 * @pramas: 1.value  需校验的数值
 *            2._len  限制的小数位数
 */
const numberDigits = function (value, _len) {
    const len = _len || 2
    var n = parseFloat(value)
    return n.toFixed(len)
}

const throttle = function (fn, delay, mustRunDelay = 0) {
    if (delay == null) return fn;
    /* istanbul ignore next */
    const timestampProvider =
        typeof performance === 'object' ? performance : Date;
    let timer = null;
    let tStart;
    return function () {
        const tCurr = timestampProvider.now();
        if (timer != null) clearTimeout(timer);
        if (!tStart) {
            tStart = tCurr;
        }
        if (mustRunDelay !== 0 && tCurr - tStart >= mustRunDelay) {
            fn.apply(this, arguments);
            tStart = tCurr;
        } else {
            const context = this;
            const args = [...arguments];
            timer = setTimeout(function () {
                timer = null;
                return fn.apply(context, args);
            }, delay);
        }
    };
}

const newSuccessMessage = function (message, seconds, showClose) {
    Message({
        type: "success",
        message: message,
        customClass: 'reset--success--message',
        center: true,
        showClose: showClose ? true : false,
        duration: (seconds == 0 || seconds) ? seconds : 3000,
    });
}
// const newErrorMessage =  function(message,seconds,showClose){
//   Message({
//     type: "error",
//     message: message,
//     customClass: 'el-message-error',
// customClass: 'reset--error--message',
//     center: true,
//     showClose:showClose?true:false,
//     duration:(seconds==0||seconds)?seconds:3000,
//   });
// }
//处理乘法精度丢失
const accMul = function (arg1, arg2) {
    if (!arg1 || !arg2) {
        arg1 = 0;
        arg2 = 0;
    }
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
const accAdd = function (arg1, arg2) {
    if (!arg1) {
        arg1 = 0;
    }
    if (!arg2) {
        arg2 = 0;
    }
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = arg2.toString().split(".")[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    console.log((arg1 * m + arg2 * m) / m);
    var ar1 = accMul(arg1, m);
    var ar2 = accMul(arg2, m);
    return (ar1 + ar2) / m;
}

//根据两个月份同一天的差值获取,同样是传入需要获取的对应年份和月份
const getMonthDays = function (year, month) {
    var stratDate = new Date(year, month - 1, 1),
        endData = new Date(year, month, 1);
    var days = (endData - stratDate) / (1000 * 60 * 60 * 24);
    return days;
}

/**
 * 取出小括号内的内容
 * @param text
 * @returns {string}
 */
const getParenthesesStr = function (text) {
    let result = ''
    if (isObjEmpty(text))
        return result
    let regex = /\((.+?)\)/g;
    let options = text.match(regex)
    if (!isObjEmpty(options)) {
        let option = options[0]
        if (!isObjEmpty(option)) {
            result = option.substring(1, option.length - 1)
        }
    }
    return result
}

const isObjEmpty = function (data) {
    return JSON.stringify(data) == "{}"
}


// 根据指定年月获取该月的第一天和最后一天
const getMonthStartEnd = function (date) {
    // console.log(date);
    let new_year = date.getFullYear();    //取当前的年份
    let month = date.getMonth();
    let new_month = month + 1;//取当前的月份
    //alert("年："+ date .getFullYear()); //获取完整的年份(4位)
    //alert("月："+ new_month);
    if (month > 12) {
        new_month -= 12;        //月份减
        new_year++;            //年份增
    }
    let d = new Date(new_year, new_month, 1);                //取当年当月中的第一天
    let lastDay = new Date(d.getTime() - 1000 * 60 * 60 * 24).getDate();//获取当月最后一天日期
    let mon = "00"
    if (d.getMonth() < 10) {
        mon = "0" + d.getMonth();
    } else {
        mon = d.getMonth();
    }
    let cfmStartDate = d.getFullYear() + '-' + mon + '-' + "0" + d.getDate();
    let cfmEndDate = d.getFullYear() + '-' + mon + '-' + lastDay;
    let obj = {
        cfmStartDate: cfmStartDate,
        cfmEndDate: cfmEndDate
    }
    // console.log(obj);
    return obj
}

//只能输入中文 英文 数字
const checkRelues = function (value) {
    return value.replace(/[^A-Za-z0-9\u4e00-\u9fa5]/g, '');
}

//不能输入中文
const check_zh = function (value) {
    return value.replace(/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g, '');
}

//不能输入中文
const  dateFormatDays= function (value) {
    let days=['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

	return days[new Date(value).getDay()];
}

export default {
    deepCopy,
    merge,
    objKeySort,
    objValSort,
    convert10To26,
    convert26To10,
    handleFile,
    dateFormat,
    numberDigits,
    formatPibTime,
    getTimeFormat,
    throttle,
    newSuccessMessage,
    accMul,
    accAdd,
    getMonthDays,
    getParenthesesStr,
    isObjEmpty,
    getMonthStartEnd,
    checkRelues,
    check_zh,
	dateFormatDays,
}
